<?php
class TasksController extends AppController {
	var $name = 'Tasks';
	var $uses=array('Task','Status','Type','Priority','User','Project','TaskNotification','ProjectUser','Field','FieldValue','Comment','FileManager','FileAttach');
	
	
	

	function admin_index($pid=0){	
		$this->Session->write('CurrentModule',$this->uses[0]);
		//permission check
		$pid=intval($pid);
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		$projectInfo=$this->getPermission(0,$pid);
		if(!isset($projectInfo['Project'])){
			$this->Session->write('error',_resource('you have not permission',true));
			$this->redirectAjaxTo('projects','mainContent');
		}
		$this->Session->write($this->uses[0].'.project_id',$pid);
		//reset page to 1
		$this->Session->write($this->uses[0].'.page',1);
		//get filter field
		$filterField=array(
		$this->uses[0].'.name'=>_resource('task name',true),
		$this->uses[0].'.description'=>_resource('task description',true),
		$this->uses[0].'.code'=>_resource('task code',true),
		'Project.name'=>_resource('project name',true)
		);
		//get status
		
		$this->set("statuses",$this->admin_nocheck_getListStatus());
					
		//default status
		if(!$this->Session->check($this->uses[0].'.status_id')){			 
			//get default status
			$status=$this->Status->find('first',array('conditions'=>array('default'=>1)));
			if(!empty($status))$this->Session->write($this->uses[0].'.status_id',$status['Status']['id']);
		}	
		
		$this->set('proj',$projectInfo['Project']);		
		$this->set('filterField',$filterField);
		$this->render('admin_index','ajax');
	}

	function admin_lists($pid=0){
		
		//get project id
		$pid=intval($pid);		
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		$this->Session->write($this->uses[0].'.project_id',$pid);
		$this->set('pid',$pid);
		$projectInfo=$this->getPermission(0,$pid);
		
		if(!isset($projectInfo['Project'])){
			$this->Session->write('error',_resource('you have not permission',true));
			$this->redirectAjaxTo('projects','mainContent');
		}
		
		
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0].'.limit')){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>$this->uses[0].'.id desc',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'project_id'=>$pid,
				'status_id'=>$this->Session->read($this->uses[0].'.status_id')
			
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);
		}

		
		
		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//===================================================================
		
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...
		$paginate=$this->Session->read($this->uses[0]);
		$paginate['conditions']['Task.project_id']=$pid;
		
		$userid=Configure::read('Session.userid');
		//$paginate['conditions']['Task.project_id']=$pid;
		if($this->Session->check($this->uses[0].'.status_id') && $this->Session->read($this->uses[0].'.status_id')>0){
			$paginate['conditions']['Status.id']=$this->Session->read($this->uses[0].'.status_id');
		}		
		//get all notify by this user
		$notify=$this->TaskNotification->getAllByUser($this->user['id']);
		$this->set('notify',$notify);
		//check if is notify, get all notify first, default is get notify first.
		if(!isset($paginate['isNotifySort'])){
			$paginate['isNotifySort']=1;
		}
		if($paginate['isNotifySort']){
			$data0=array();		
			$limit=$paginate['limit'];
			$pageCount=1;
			$count=0;
			$currentPage=$paginate['page'];
			
			//query
			//get all count:
			$paginate['conditions']['Task.id']=$notify;			
			$countNotify=$this->{$this->uses[0]}->find('count',array('conditions'=>$paginate['conditions']));
			$paginate['conditions']['NOT']['Task.id']=$notify;
			unset($paginate['conditions']['Task.id']);
			$countNoNotify=$this->{$this->uses[0]}->find('count',array('conditions'=>$paginate['conditions']));
			$count=$countNoNotify+$countNotify;
			$pageCount=ceil($count/$limit);
			unset($paginate['page']);
			//get notify by page
			//check if current page is include notify
			if($countNotify>($currentPage-1)* $limit){
				//get <limit> notify record
				unset($paginate['conditions']['NOT']);
				$paginate['conditions']['Task.id']=$notify;
				$paginate['limit']=(($currentPage-1)* $limit).','.$limit;
				
				$data0=$this->{$this->uses[0]}->find('all',$paginate);
				//t($paginate);
				//check if is equal <limit>:
				$lack=$limit-count($data0);
				if($lack>0){
					//get lack record (no notify record)
					unset($paginate['conditions']['Task.id']);
					$paginate['conditions']['NOT']['Task.id']=$notify;
					$paginate['limit']=$lack;
					foreach($this->{$this->uses[0]}->find('all',$paginate) as $k=>$v)$data0[]=$v;
				}				
			}
			else{
				unset($paginate['conditions']['Task.id']);
				$paginate['conditions']['NOT']['Task.id']=$notify;
				$start=($currentPage-1)*$limit-$countNotify;	
							
				$paginate['limit']=$start.','.$limit;
				
				$data0=$this->{$this->uses[0]}->find('all',$paginate);
			}
			
			$this->params->params['paging'][$this->uses[0]]['limit']=$limit;
			$this->params->params['paging'][$this->uses[0]]['page']=$currentPage;
			$this->params->params['paging'][$this->uses[0]]['pageCount']=$pageCount;
			$this->params->params['paging'][$this->uses[0]]['count']=$count;
			//t($this->params);
			
		}
		else{
			//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
			//lay data da duoc phan trang va truyen vao bien $data0		
			$this->paginate=$paginate;
			$data0=$this->paginate($this->uses[0]);			
			t($this->params);
		}
		
		
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);

		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website.
		$this->render('admin_lists','ajax');
	}

	function admin_add($locale=null){
		//get project id
		$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		$projectInfo=$this->getPermission(0,$pid);
		if(empty($projectInfo)){
			$this->Session->write('error',_resource('you have not permission',true));
			$this->redirectAjaxTo('projects','mainContent');
		}
		$proj=$projectInfo['Project'];
		$isInsert=false;
			
		//check is manager				
		if(!Configure::read('Session.isSa') && !Configure::read('Session.isAdmin') && !Configure::read('Session.isManager') && !Configure::read('Session.isQA')){			
			$this->Session->write('error',_resource('You have not permission',true));
			$this->redirectAjaxTo('tasks/lists','listContent');
		}
		
		if(!empty($this->data)){
			
			$data=$this->data;
			$data[$this->uses[0]]['user_id']=$this->user['id'];
			if(isset($data[$this->uses[0]]['assignees']))$data[$this->uses[0]]['assignees']=$data[$this->uses[0]]['assignees'];
			if($this->{$this->uses[0]}->create($data) && $this->{$this->uses[0]}->validates()){
				
				//get default status
				$status=$this->Status->find('first',array('conditions'=>array('default'=>1)));
				if(isset($status['Status']['id']))$data[$this->uses[0]]['status_id']=$status['Status']['id'];
				
				if($this->{$this->uses[0]}->save($data)) {
					
					//update task code
					$lastid=$this->{$this->uses[0]}->getLastInsertID();	
					$maxCodeTask=$this->{$this->uses[0]}->find('first',array('conditions'=>'Project.id='.$proj['Project']['id'],'order'=>$this->uses[0].'.code desc'));
					if(isset($maxCodeTask[$this->uses[0]]['code']))$nextId=$maxCodeTask[$this->uses[0]]['code']+1;
					else $nextId=1;
					//update task code	
					$this->{$this->uses[0]}->updateAll(array($this->uses[0].'.code'=>$nextId,'taskcode'=>'"'.$proj['Project']['code'].'-'.$nextId.'"','project_id'=>$pid),array('Task.id'=>$lastid));
					
					
					//update fields
					if(isset($data['Field'])){
						//t($data['Field']);
						foreach($data['Field'] as $k=>$v){
							if(!empty($v['value'])){
								$v['task_id']=$lastid;
								App::import('Model','FieldValue');
								$FieldValue =& new FieldValue();
								//$Field->create($data);
								$FieldValue->save($v);
							}
						}
					}
					//insert file attach
					if(isset($data['FileAttach'])){
						//t($data['Field']);
						foreach($data['FileAttach'] as $k=>$v){
							if(!empty($v['id'])){
								$insertdata['user_id']=$this->user['id'];
								$insertdata['file_id']=$v['id'];
								$insertdata['task_id']=$lastid;		
								$this->FileAttach->create($insertdata);
								$this->FileAttach->save();
								//mount to file
								$this->FileManager->updateAll(array('mount'=>'mount + 1'),array('id'=>$v['id']));
							}
						}
					}
					
					//add watch
					//add watch owner
					$this->TaskNotification->addWatch($this->user['id'],$lastid);
					if(isset($data[$this->uses[0]]['watches'])){
						foreach($data[$this->uses[0]]['watches'] as $k=>$v){
							$this->TaskNotification->addWatch($v,$lastid);
						}
					}
					
					//add notify for assignee
					//t($proj['Project']['manager']);					
					if(isset($data[$this->uses[0]]['assignees']))$this->TaskNotification->addNotify($data[$this->uses[0]]['assignees'],$lastid);
					//addwatch for manager
					$this->TaskNotification->addNotify($proj['Project']['manager'],$lastid);
					
					
					//notify all except current user
					$this->TaskNotification->notify($this->user['id'],$lastid);
					
					
					$this->Session->write('message',_resource('insert data successful',true));					
					$this->redirectAjaxTo('tasks/lists','listContent');
					
				} else {
					$this->Session->write('error',_resource('can not insert data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}
		else{
			//get all field
			if(!empty($proj['Project']['fields'])){				
				$option['joins']=array(
					array('table'=>'field_values',
						'type'=>'left',
						'alias'=>'FieldValue',
						'conditions'=>array('task_id'=>$id,
							'Field.id=FieldValue.field_id'
						)
					)	
				);
				$option['fields']=array('Field.id','Field.name','Field.value','Field.fieldvalue_id');
				$option['conditions']=array('Field.id'=>explode(',', $proj['Project']['fields']));
				
				$this->Field->virtualFields=array('value'=>'FieldValue.value','fieldvalue_id'=>'FieldValue.id');
				$fields=$this->Field->find('all',$option);			
				if(count($fields)>0){
					foreach($fields as $k=>$v){
						$data['Field'][$v['Field']['id']]=array('id'=>$v['Field']['fieldvalue_id'],'field_id'=>$v['Field']['id'],'name'=>$v['Field']['name'],'value'=>$v['Field']['value']);
					}
				}
				$this->data=$data;
			}
		}

		//get all type		
		$types=$this->Type->find('list',array('order'=>'view_order desc'));
		$this->set('types',$types);
		$types=$this->Type->find('first',array('conditions'=>array('default'=>1)));
		if(isset($types['Type']['id']))$this->set('defaulttype',$types['Type']['id']);
		//get default type
		$defaultType=$this->Type->find('first',array('conditions'=>array('default'=>1)));
		$defaultTypeId=0;
		if(isset($defaultType['Type']['id']))$defaultTypeId=$defaultType['Type']['id'];
		$this->set('defaultTypeId',$defaultTypeId);
		
		//get all prior		
		$priors=$this->Priority->find('list',array('order'=>'view_order desc'));
		$this->set('priors',$priors);
		$priors=$this->Priority->find('first',array('conditions'=>array('default'=>1)));
		if(isset($priors['Priority']['id']))$this->set('defaultprior',$priors['Priority']['id']);
		//get default prior
		$defaultPrior=$this->Priority->find('first',array('conditions'=>array('default'=>1)));
		$defaultPriorId=0;
		if(isset($defaultPrior['Priority']['id']))$defaultPriorId=$defaultPrior['Priority']['id'];
		$this->set('defaultPriorId',$defaultPriorId);
		
		//get all user in current project
		if(!empty($proj['Project']['users']))
		{
			$users=$this->User->getUserByArrayUserId(explode(',',$proj['Project']['users']));
			$this->set('users',$users);
		}			
		$this->set('proj',$proj);
			
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
	}

	function admin_edit($id=null,$locale=null){		
		
		$isInsert=false;
		$taskinfo=$this->getPermission(intval($id));	
		if(!isset($taskinfo['Task']) && !Configure::write('Session.isSa') && !Configure::write('Session.isAdmin') && !Configure::write('Session.isManager')  && !Configure::write('Session.isAssignee')  ){
			$this->Session->write('error',_resource('You have not permission',true));
			if($this->Session->read('CurrentModule')=='Home')$this->redirectAjaxTo('homes/lists','listContent');
			elseif($this->Session->read('CurrentModule')=='Task') $this->redirectAjaxTo('tasks/lists','listContent');
		}
		$task=$taskinfo['Task'];
		$proj=$taskinfo['Project'];
		
		
		if(!empty($this->data)){			
			$data=$this->data;
			if(isset($data[$this->uses[0]]['assignees']))$data[$this->uses[0]]['assignees']=$data[$this->uses[0]]['assignees'];
			if($this->{$this->uses[0]}->validates($data)){				
				if($this->{$this->uses[0]}->save($data)) {					
					//update fields
					if(isset($data['Field'])){
						//t($data['Field']);
						foreach($data['Field'] as $k=>$v){
							$v['task_id']=$id;
							App::import('Model','FieldValue');
							$FieldValue =& new FieldValue();
							//$Field->create($data);
							$FieldValue->save($v);
						}
					}
					//update file
					//get old file					
					$oldfile=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
					//convert to id=>array
					if(!empty($oldfile)){
						foreach($oldfile as $k=>$v){
							$oldfileConverted[$v['FileAttach']['id']]=$v;
						}
					}
					//check new file
					$updateMsg='';
					if(isset($data['FileAttach'])){
						//t($data['Field']);
						$updateMsg='Add new files:<br />';
						foreach($data['FileAttach'] as $k=>$v){
							if(!empty($v['id']) && !isset($oldfileConverted[$v['id']])){
								$insertdata['user_id']=$this->user['id'];
								$insertdata['file_id']=$v['id'];
								$insertdata['task_id']=$data[$this->uses[0]]['id'];		
								$this->FileAttach->create($insertdata);
								$this->FileAttach->save();
								//mount to file
								$this->FileManager->updateAll(array('mount'=>'mount + 1'),array('id'=>$v['id']));
								$updateMsg.=$data['FileAttach']['name'];
							}
							else{
								//file not change, remove in oldfileConvert list
								unset($oldfileConverted[$v['id']]);
							}
						}
					}
					
					//delete old file
					if(!empty($oldfileConverted)){
						$updateMsg.='Delete files:<br />';
						foreach($oldfileConverted as $k=>$v){
							$this->FileAttach->deleteAll(array('FileAttach.id'=>$k),false);
							//unmount
							$this->FileManager->updateAll(array('mount'=>'mount - 1'),array('id'=>$v['FileManager']['id']));
							$updateMsg.=$v['FileManager']['name'];							
						}
					}
					
					//add watch
					//add watch owner
					$this->TaskNotification->addWatch($this->user['id'],$this->data[$this->uses[0]]['id']);
					
					if(isset($data[$this->uses[0]]['watches'])){
						foreach($data[$this->uses[0]]['watches'] as $k=>$v){
							$this->TaskNotification->addWatch($v,$this->data[$this->uses[0]]['id']);
						}
					}
					
					//addnotify for assignee												
					if(isset($data[$this->uses[0]]['assignees']) && $data[$this->uses[0]]['assignees']!=$task[$this->uses[0]]['assignees']){
						//t($data[$this->uses[0]]['assignees'].'-'.$data[$this->uses[0]]['id']);
						$this->TaskNotification->addNotify($data[$this->uses[0]]['assignees'],$data[$this->uses[0]]['id']);
						//remove watch for oldassignee
						$this->TaskNotification->removeNotify($task[$this->uses[0]]['assignees'],$data[$this->uses[0]]['id']);
						$this->TaskNotification->notifyToUserId($data[$this->uses[0]]['assignees'],$data[$this->uses[0]]['id']);
							
					}
					
					if(!empty($updateMsg)){
						$updateMsg='<b>Task update:</b><br/>'.$updateMsg;
						$this->Comment->addComment($updateMsg,$this->user['id'],$data['FileAttach']['task_id']);
					}
					
					
					$this->Session->write('message',_resource('update data successful',true));					
					$this->data=null;					
					$isInsert=true;					
					$this->redirectAjaxTo('tasks/detail/'.$taskinfo['Task']['Task']['id'],'addContent');
					
					

				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			
					
			
			//get all field
			if(!empty($proj['Project']['fields'])){				
				$option['joins']=array(
					array('table'=>'field_values',
						'type'=>'left',
						'alias'=>'FieldValue',
						'conditions'=>array('task_id'=>$id,
							'Field.id=FieldValue.field_id'
						)
					)	
				);
				$option['fields']=array('Field.id','Field.name','Field.value','Field.fieldvalue_id');
				$option['conditions']=array('Field.id'=>explode(',', $proj['Project']['fields']));
				
				$this->Field->virtualFields=array('value'=>'FieldValue.value','fieldvalue_id'=>'FieldValue.id');
				$fields=$this->Field->find('all',$option);			
				if(count($fields)>0){
					foreach($fields as $k=>$v){
						$task['Field'][$v['Field']['id']]=array('id'=>$v['Field']['fieldvalue_id'],'field_id'=>$v['Field']['id'],'name'=>$v['Field']['name'],'value'=>$v['Field']['value']);
					}
				}
				
			}
			//get all file attach
			$fileattach=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
			if(!empty($fileattach)){
				foreach($fileattach as $k=>$v){
					$fileitem['id']=$v['FileAttach']['id'];
					$fileitem['name']=$v['FileManager']['name'];
					if($v['User']['username']!=$this->user['username'])
						$fileitem['username']=$v['User']['username'];
					$task['FileAttach'][]=$fileitem;		
				}
			}
			$this->data=$task;
		}

			$types=$this->Type->find('list',array('order'=>'view_order desc'));
			$this->set('types',$types);
			//get all status		
			
			$this->set('statuses',$this->admin_nocheck_getListStatus());
			//get all prior		
			$priors=$this->Priority->find('list',array('order'=>'view_order desc'));
			$this->set('priors',$priors);
			//get all Project
			$projects=$this->Project->find('list');
			$this->set('projects',$projects);
			
			//get all user in current project
			if(isset($proj['Project']['users']) && !empty($proj['Project']['users']))
			{
				$users=$this->User->getUserByArrayUserId(explode(',',$proj['Project']['users']));
				$this->set('users',$users);
			}
		
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
	}

function admin_detail($id=0){
		
		$taskinfo=$this->getPermission(intval($id));	
		if(isset($taskinfo['Task'])){
			
			//unnotify
			$this->TaskNotification->unnotify($this->user['id'],$id);
			$task=$taskinfo['Task'];
			$proj=$taskinfo['Project'];
			//get all attach file
			//get all file attach
			$fileattach=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
			$task['FileAttach']=$fileattach;
			$this->set('data',$task);
			
			
			unset($option);
			
			//get all field
			
			if(!empty($proj['Project']['fields'])){
				$option['joins']=array(
					array('table'=>'field_values',
						'type'=>'left',
						'alias'=>'FieldValue',
						'conditions'=>array('task_id'=>$id,
							'Field.id=FieldValue.field_id'
						)
					)	
				);
				$option['fields']=array('FieldValue.id','Field.id','Field.name','Field.value');
				if(!empty($proj['Project']['fields']))$option['conditions']=array('Field.id'=>explode(',', $proj['Project']['fields']));			
				$this->Field->virtualFields=array('value'=>'FieldValue.value');
				$fields=$this->Field->find('all',$option);
				
				$this->set('fields',$fields);	
			}
			//get all status		
			$this->set('statuses',$this->admin_nocheck_getListStatus());
			$this->set('proj',$proj);
			
			//get all user in current project
			if(isset($proj['Project']['users']) && !empty($proj['Project']['users']))
			{
				$users=$this->User->getUserByArrayUserId(explode(',',$proj['Project']['users']));
				$this->set('users',$users);
			}
			//get watch status
			$this->TaskNotification->recursive=-1;
			$watch=$this->TaskNotification->find('first',array('conditions'=>array('TaskNotification.task_id'=>$id,'TaskNotification.user_id'=>$this->user['id'])));
			if(!isset($watch['TaskNotification']['watch']))$watchStatus=0;
			else $watchStatus=intval($watch['TaskNotification']['watch']);
			$this->set('watchStatus',$watchStatus);
			
			//check is there sourcecontrol
			App::uses('SourceControl', 'Model');
			$SourceControl=new SourceControl();
			$sc=$SourceControl->find('first',array('conditions'=>array('project_id'=>$proj['Project']['id'],'active'=>1)));			
			$this->set('sc',$sc);
			App::uses('Host', 'Model');
			$Host=new Host();
			$host=$Host->find('first',array('conditions'=>array('project_id'=>$proj['Project']['id'],'published'=>1)));
			if(!empty($host) && $this->checkUserInString($host['Host']['users'])){				
				$this->set('host',$host);
			}
		}
		else{
			$this->Session->write('error',_resource('can not find data',true));
			if($this->Session->read('CurrentModule')=='Home')$this->redirectAjaxTo('homes/lists','listContent');
			elseif($this->Session->read('CurrentModule')=='Task') $this->redirectAjaxTo('tasks/lists','listContent');
		}
		
		
	}
	
	function admin_watch($taskid=0){
		$taskid=intval($taskid);
		if($taskid){
			$taskInfo=$this->getPermission($taskid);
			if(!isset($taskInfo['Task']) || !Configure::read('Session.isJoin')){
				$this->Session->write('error',_resource('You have not permission',true));
				$this->redirectAjaxTo('tasks/lists','listContent');
			}
			$this->TaskNotification->addWatch($this->user['id'],$taskid);			
		}
		$this->set('taskid',$taskid);
		$this->render('admin_watch','ajax');
	}
	
	function admin_unwatch($taskid=0){
		$taskid=intval($taskid);
		if($taskid){			
			$this->TaskNotification->removeWatch($this->user['id'],$taskid);			
		}
		$this->set('taskid',$taskid);
		$this->set('unwatch',1);
		$this->render('admin_watch','ajax');
	}
	
	function admin_changeStatus($id=0){
		if(empty($this->data)){	
			exit;
		}
		$user=$this->user;
		$taskinfo=$this->getPermission(intval($id));	
		if(!isset($taskinfo['Task']) && !Configure::write('Session.isSa') && !Configure::write('Session.isAdmin') && !Configure::write('Session.isManager')  && !Configure::write('Session.isAssignee')  ){
			$this->Session->write('error',_resource('You have not permission',true));
			if($this->Session->read('CurrentModule')=='Home')$this->redirectAjaxTo('homes/lists','listContent');
			elseif($this->Session->read('CurrentModule')=='Task') $this->redirectAjaxTo('tasks/lists','listContent');
		}
		$task=$taskinfo['Task'];
		$proj=$taskinfo['Project'];
		
		//update progress:
		$updateMsg='';
		$updatedata=array();
		//status
		
		//dev cannot change status		
		if($this->data['Task']['status_id']!=$this->data['Task']['oldstatus_id'] && (Configure::write('Session.isSa') || Configure::write('Session.isAdmin') || Configure::write('Session.isManager') || Configure::write('Session.isOwner')) ){
			$updatedata['status_id']=$this->data['Task']['status_id'];
			$listStatus=$this->Status->find('list',array('fields'=>'id,name'));
			$updateMsg='Status: '.$listStatus[$this->data['Task']['oldstatus_id']].' ==> '.$listStatus[$this->data['Task']['status_id']].'<br />';
			$updateMsg='<b>Task update:</b><br/>'.$updateMsg;	
			$this->Comment->addComment($updateMsg,$this->user['id'],$task['Task']['id'],false);
			$updateMsg='';			
		}
		
		//assignee
		if(isset($this->data['Task']['assignees']) && $this->data['Task']['assignees']!=$task['Task']['assignees']){
			$updatedata['assignees']=$this->data['Task']['assignees'];
			//addwatch for oldassignee
			$this->TaskNotification->addNotify($this->data['Task']['assignees'],$task[$this->uses[0]]['id']);
			//remove watch for oldassignee
			$this->TaskNotification->removeNotify($task[$this->uses[0]]['assignees'],$task[$this->uses[0]]['id']);
			$listUser=$this->User->find('list',array('fields'=>'id,username','conditions'=>'id ='.$this->data['Task']['assignees']));			
			$updateMsg.='Assign to: '.$listUser[$this->data['Task']['assignees']].'<br />';
			$this->TaskNotification->addNotify($this->data['Task']['assignees'],$task['Task']['id']);			
		}
		//field
		if(isset($this->data['Field'])){			
			foreach($this->data['Field'] as $k=>$v){
				if($v['value']!=$v['oldvalue']){	
					if(!empty($v['fieldvalue_id'])){
						$this->FieldValue->updateAll(array('value'=>'\''.$v['value'].'\''),array('id'=>$v['fieldvalue_id']));
					}
					else{
						$fielddata['value']=$v['value'];
						$fielddata['field_id']=$v['field_id'];
						$fielddata['task_id']=$task['Task']['id'];
						$this->FieldValue->create($fielddata);
						$this->FieldValue->save();
					}
					$updateMsg.=$k.': '.$v['value'].'<br />';
				}				
			}
		}
		//update task
		if(!empty($updatedata))$this->Task->updateAll($updatedata,array('Task.id'=>$task['Task']['id']));
		//add comment
		if(!empty($updateMsg)){
			$updateMsg='<b>Task update:</b><br/>'.$updateMsg;
			$this->Comment->addComment($updateMsg,$this->user['id'],$task['Task']['id']);
			$this->Session->write('message',_resource('Task was updated',true));
			
		}
		
		$this->redirectAjaxTo('tasks/detail/'.$taskinfo['Task']['Task']['id'],'addContent');
	}
	
	function admin_removefileattach($id = null) {
		$this->autoRender=false;
		$id=intval($id);
		$data=$this->FileAttach->find('first',array('conditions'=>'FileAttach.id='.$id));
		if($id>0 && !empty($data) && $data['FileAttach']['user_id']==$this->user['id']){
			//remove
			$this->FileAttach->deleteAll(array('FileAttach.id'=>$id));
			$this->FileManager->updateAll(array('mount'=>'mount - 1'),array('id'=>$data['FileAttach']['file_id']));
			$updateMsg=$data['FileManager']['name'];
			$updateMsg='<b>Task update:</b><br/>Deleted file:<br />'.$updateMsg;
			$this->Comment->addComment($updateMsg,$this->user['id'],$data['FileAttach']['task_id']);
		}
		$this->redirectAjaxTo('comments/lists','commentContent');
		
	}
function admin_delete($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=array_keys($_POST['check']);
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[]=$id;
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->deleteAll(array($this->uses[0].'.id'=>$id_arr),false);			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();		
	}

	
	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}

	function admin_page($page=1,$pid=0){
		$pid=intval($pid);
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists($pid);
	}

	function admin_display($limit=0,$pid=0){
		$pid=intval($pid);
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists($pid);
	}

	function admin_filter($pid=0){
		$pid=intval($pid);
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			//$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';
				$this->Session->write($this->uses[0].'.page',1);				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		
		//t($this->Session->read('Home.status_id'));
		$this->admin_lists($pid);
	}
	
	function admin_status($statusid=0,$pid=0){
		//status
		$pid=intval($pid);
		if($pid==0)$pid=intval($this->Session->read($this->uses[0].'.project_id'));
		$statusid=intval($statusid);
		$this->Session->write($this->uses[0].'.status_id',$statusid);
		$this->Session->write($this->uses[0].'.page',1);
		$this->admin_lists($pid);
	}
	/*
	 * ham dung de save thu tu cua tung mau tin
	 */
function admin_save(){
		if($this->request->is('post')){
			foreach($_POST['order'] as $k=>$v){
				if(intval($v)){
					//set view order for category
					$this->{$this->uses[0]}->updateAll(array($this->uses[0].'.view_order'=>intval($v)),array($this->uses[0].'.id'=>$k));
				}
			}
		}
		$this->Session->write('message',_resource('view order has been update',true));
		$this->admin_lists();
	}

	/*
	 * ham dung khi co su dung chuc nang da ngon ngu
	 * dung de change locale cua he thong
	 * tham so truyen vao la locale cua ngon ngu
	 */
	function admin_changeLocale($locale=null){
		//luu session
		if($locale){
			$this->Session->write('adminLang',$locale);
		}
		//reload lai luoi de apply locale vua change
		$this->admin_lists();
	}

	
	function admin_selCat($id=null) {
		//kiem tra neu submit tu form
		//luu dieu kien chon
		$conditions=null;
		$conditions=$this->Session->read($this->uses[0].'.conditions');
		$conditions[$this->uses[0].'.'.$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']]=intval($id);
		if($id!=null){
			//luu sesssion de giu lai gia da chon
			$this->Session->write($this->uses[0].'.catid',intval($id));
		}
		else{
			$this->Session->write($this->uses[0].'.catid','');
			unset($conditions[$this->uses[0].'.'.$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']]);
		}
		$this->Session->write($this->uses[0].'.conditions',$conditions);
		$this->admin_index();
	}

	function admin_nocheck_getListStatus(){
		$statuses=$this->Status->find('list');
		$statuses=array('0'=>'All')+$statuses;
		return $statuses;
	}
	
}
?>
